<template>
  <div class="app-container">
    <div :class="['filter-container', 'open']" style="height: 55px !important">
      <!-- 展开状态下的筛选框 -->
      <el-form ref="form" :inline="true" :model="form" label-width="100px">
        <el-form-item label="项目骨架名称">
          <el-input v-model="form.name" clearable placeholder />
        </el-form-item>
        <el-form-item label="项目骨架类型">
          <el-select v-model="form.type" placeholder clearable>
            <el-option
              v-for="item in importanceOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" label-width="80px">
          <el-date-picker
            v-model="form.startTime"
            type="date"
            placeholder="选择开始日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions1"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" label-width="80px">
          <el-date-picker
            v-model="form.endTime"
            type="date"
            placeholder="选择结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions2"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" label-width="50px">
          <el-select
            v-model="form.status"
            style="width: 165px"
            clearable
            placeholder
          >
            <el-option
              v-for="item in sortOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
            >查询</el-button
          >
          <el-button
            class="filter-item"
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-edit-outline"
            @click="handleReset"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-button
      class="filter-item"
      type="primary"
      style="margin-bottom: 15px"
      @click="handleCreate"
      >新增</el-button
    >
    <el-row
      :gutter="12"
      style="height: calc(100vh - 260px); overflow-y: scroll"
    >
      <el-col :span="6" v-for="item in list" :key="item.id">
        <el-card shadow="always" style="cursor: pointer; margin-bottom: 10px">
          <div @click="handleLook(item)">
            <p class="oneStyle">
              {{ item.name }}-{{
                item.type == 1
                  ? "单体模型"
                  : item.type == 2
                  ? "SOA模型"
                  : "微服务模型"
              }}
            </p>
            <p
              class="threeStyle"
              style="display: flex; justify-content: space-between"
            >
              <span>创建人：{{ item.createUserName }}</span>
              <span>{{ item.create_Time }}</span>
            </p>
            <div style="display: flex; justify-content: space-between">
              <span class="threeStyle">项目管理员：{{ item.admin_Name }}</span>
              <p
                class="icons_Style"
                :style="{
                  color: item.status == 1 ? '#67c23a' : '#f56c6c',
                  background:
                    item.status == 1
                      ? 'rgb(232, 255, 234)'
                      : 'rgb(255, 236, 232)',
                }"
              >
                <i
                  style="margin-right: 3px"
                  :class="
                    item.status == 1 ? 'el-icon-success' : 'el-icon-error'
                  "
                ></i>
                {{ item.status == 1 ? "已上线" : "未上线" }}
              </p>
            </div>
            <div style="text-align: right">
              <el-button type="primary" @click.stop="handleEdit(item)"
                >编辑</el-button
              >
              <el-button type="danger" @click.stop="handleDelete(item)"
                >删除</el-button
              >
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="form.page"
      :limit.sync="form.limit"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="30%"
      v-if="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
      >
        <el-form-item label="项目骨架名称" prop="name">
          <el-input
            v-model="temp.name"
            clearable
            :disabled="isDisabled"
            placeholder
          />
        </el-form-item>
        <el-form-item label="项目骨架类型">
          <el-select
            v-model="temp.type"
            placeholder
            clearable
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in importanceOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目管理员">
          <el-select
            v-model="temp.adminId"
            placeholder
            clearable
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in templateLists"
              :key="item.userId"
              :label="item.username"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="骨架状态">
          <el-select
            v-model="temp.status"
            :disabled="isDisabled"
            clearable
            placeholder
          >
            <el-option
              v-for="item in sortOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目骨架描述">
          <el-input
            type="textarea"
            v-model="temp.remark"
            :disabled="isDisabled"
            clearable
            placeholder
          ></el-input>
        </el-form-item>
        <!-- :action="actionUrl" :http-request="httpRequest"-->
        <el-form-item label="上传" prop="fileList">
          <el-upload
            class="upload-demo"
            drag
            :action="actionUrl"
            accept=".zip"
            :file-list="temp.fileList"
            :disabled="isDisabled"
            :headers="headers"
            :on-success="handleAvatarSuccess"
            :on-error="onError"
            :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传ZIP文件，且不超过10MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="!isDisabled">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  projectDelete,
  findPageprojecttemplate,
  projectSSave,
  projectsupdate,
  projectgenerate,
  projectupload,
} from "@/api/article";
import { getUserList } from "@/api/permission";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination 分页组件
import { getToken } from "@/utils/auth";
const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" },
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "LayoutTable",
  components: { Pagination },
  directives: { waves }, // 指令

  data() {
    const validatorFile = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传ZIP文件"));
      } else {
        callback();
      }
    };
    return {
      headers: {
        token: getToken(),
      },
      actionUrl: `${process.env.VUE_APP_BASE_API}/projectManage/project/upload`,
      peizhiVisible: false,
      // 筛选框的 form 表单
      isDisabled: false,
      dataTime: [],
      form: {
        name: "",
        type: "",
        startTime: "",
        endTime: "",
        status: "",
        page: 1,
        limit: 20,
      },
      tableKey: 0,
      list: [], // 表格数据
      total: 0, // 总条数
      listLoading: true, // 表格加载数据时的 loading
      importanceOptions: [
        {
          code: 1,
          name: "单体模型",
        },
        {
          code: 2,
          name: "SOA模型",
        },
        {
          code: 3,
          name: "微服务模型",
        },
      ],
      templateLists: [],
      businessLists: [
        {
          code: 1,
          name: "标准后台类",
        },
        {
          code: 2,
          name: "ERP类",
        },
        {
          code: 3,
          name: "OA类",
        },
      ],
      calendarTypeOptions, // 类型的下拉选内容
      sortOptions: [
        {
          code: 1,
          name: "已上线",
        },
        {
          code: 2,
          name: "未上线",
        },
      ],
      statusOptions: ["published", "draft", "deleted"], // 新增和修改弹框里面的 Status 下拉框
      temp: {
        // 新增和修改弹框 的 form 表单
        name: "",
        type: "",
        adminId: "",
        status: "",
        remark: "",
        path: "",
        fileName: "",
        fileList: [],
      },
      rules: {
        // 表单验证
        name: [
          { required: true, message: "请输入项目骨架名称", trigger: "blur" },
        ],
        // message: '请上传zip文件',
        fileList: [
          { required: true, trigger: "change", validator: validatorFile },
        ],
      },
      dialogFormVisible: false, // 弹框展示隐藏
      dialogStatus: "", // 弹框新增或者修改
      textMap: {
        // 弹框的标题
        update: "编辑",
        create: "新增",
      },
      downloadLoading: false, // 导出按钮 的 loading
      pickerOptions1: {
        disabledDate: (time) => {
          if (this.form.endTime) {
            return time.getTime() > new Date(this.form.endTime).getTime();
          }
        },
      },
      pickerOptions2: {
        disabledDate: (time) => {
          if (this.form.startTime) {
            return (
              time.getTime() <
              new Date(this.form.startTime).getTime() - 86400000
            );
          }
        },
      },
    };
  },
  async created() {
    await this.getUserList();
    this.getList();
  },
  methods: {
    beforeAvatarUpload(file) {
      const index = file.name.lastIndexOf(".");
      const iszip = file.name.slice(index) === ".zip";
      const isLt2M = file.size / 1024 / 1024 <= 10;
      if (!iszip) {
        this.$message.error("上传文件只能是ZIP格式");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过10MB");
      }
      return iszip && isLt2M;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 获取表格数据
    getList() {
      this.listLoading = true;
      findPageprojecttemplate(this.form).then((response) => {
        this.list = response.data.list;
        this.list.forEach((item) => {
          if (item.adminId) {
            const obj = this.templateLists.find(
              (v) => v.userId === item.adminId
            );
            this.$set(item, "admin_Name", obj ? obj.username : "");
          }
          if (item.createTime) {
            item.create_Time = parseTime(item.createTime);
          }
        });
        this.total = response.data.totalCount;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    async getUserList() {
      const res = await getUserList();
      if (res) {
        this.templateLists = res.data;
      } else {
        this.templateLists = [];
      }
    },
    handleLook(item) {
      this.isDisabled = true;
      this.dialogFormVisible = true;
      this.temp = JSON.parse(JSON.stringify(item));
      if (item.fileName) {
        this.$set(this.temp, "fileList", [
          {
            name: item.fileName,
          },
        ]);
      } else {
        this.$set(this.temp, "fileList", []);
      }
      this.temp.status = this.temp.status || null;
    },
    // 重新获取表格数据 页码归为1
    handleFilter() {
      this.form.page = 1;
      if (this.dataTime.length) {
        this.form.startTime = this.dataTime[0] || "";
        this.form.endTime = this.dataTime[0] || "";
      } else {
        this.startTime = "";
        this.endTime = "";
      }
      this.getList();
    },
    handleReset() {
      this.dataTime = [];
      this.form = {
        name: "",
        type: "",
        startTime: "",
        endTime: "",
        status: "",
        page: 1,
        limit: 20,
      };
      this.getList();
    },
    // 新增数据-打开弹框
    handleCreate() {
      this.isDisabled = false;
      this.dialogStatus = "create";
      this.temp = {
        name: "",
        type: "",
        adminId: "",
        status: "",
        remark: "",
        path: "",
        fileName: "",
        fileList: [],
      };
      this.dialogFormVisible = true;
    },
    handleEdit(item) {
      this.isDisabled = false;
      this.dialogFormVisible = true;
      this.dialogStatus = "update";
      this.temp = JSON.parse(JSON.stringify(item));
      if (item.fileName) {
        this.$set(this.temp, "fileList", [
          {
            name: item.fileName,
          },
        ]);
      } else {
        this.$set(this.temp, "fileList", []);
      }
      this.temp.status = this.temp.status || null;
    },
    // 新增数据-表单提交
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          projectSSave(this.temp).then((res) => {
            if (res?.code === 200) {
              this.dialogFormVisible = false;
              this.$message({
                //message: res.message,
                message: "新增成功",
                type: "success",
              });
              this.getList();
            }
          });
        }
      });
    },
    // 修改 -- 提交表单
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          projectsupdate(this.temp).then((res) => {
            if (res?.code === 200) {
              this.dialogFormVisible = false;
              this.$message({
                //message: res.message,
                message: "修改成功",
                type: "success",
              });
              this.getList();
            }
          });
        }
      });
    },
    async handleDelete(item) {
      this.$confirm(`确定要进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await projectDelete(item.id);
        if (res) {
          this.$message({
            //message: res.message,
            message: "删除成功",
            type: "success",
          });
          this.getList();
        }
      });
    },
    async handleGenerate(item) {
      this.$confirm(`确定要进行生成操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await projectgenerate(item.id);
        if (res?.code === 200) {
          this.$message({
            //message: res.message,
            message: res.message,
            type: "success",
          });
          this.getList();
        }
      });
    },
    // async httpRequest(item) {
    //   const formDate = new FormData();
    //   formDate.append("file", item.file);
    //   this.temp.path = "";
    //   const res = await projectupload(formDate);
    //   if (res?.code === 200) {
    //     this.temp.path = res.data;
    //     this.$message({
    //       //message: res.message,
    //       message: "上传成功",
    //       type: "success",
    //     });
    //   }
    // },
    handleAvatarSuccess(res, file, fileList) {
      this.temp.path = res.data;
      this.temp.fileList = fileList;
      this.temp.fileName = file.name;
      this.$message({
        //message: res.message,
        message: "上传成功",
        type: "success",
      });
      this.$refs["dataForm"].validateField("fileList");
    },
    onError(err, file, fileList) {
      this.temp.path = "";
      this.temp.fileList = fileList;
      this.temp.fileName = "";
      this.$message({
        //message: res.message,
        message: "上传失败",
        type: "error",
      });
    },
    //
    handleRemove(file, fileList) {
      if (file && file.status === "success") {
        //这个判断解决element上传组件before-upload返回false自动调用before-remove on-remove钩子问题
        this.temp.fileName = "";
        this.temp.fileList = fileList;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import "~@/styles/layout-table.scss";
$rowLength: 2;
@media all and (min-width: 1659px) {
  $rowLength: 2;
  @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
  $rowLength: 3;
  @include calculation($rowLength: $rowLength);
}
</style>
